package middle

import (
	"gen-code-v2/internal/consts"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"net/http"
)

func MiddlewareHandlerResponse(r *ghttp.Request) {
	r.Middleware.Next()

	// There's custom buffer content, it then exits current handler.
	if r.Response.BufferLength() > 0 {
		return
	}
	var (
		msg  = "操作成功！"
		ctx  = r.Context()
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = http.StatusOK
	)
	if err != nil {
		code = http.StatusInternalServerError
		msg = err.Error()
	} else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
		msg = http.StatusText(r.Response.Status)
		switch r.Response.Status {
		case http.StatusNotFound:
			code = http.StatusNotFound
		case http.StatusForbidden:
			code = http.StatusNotFound
		}
	}
	resultData := g.Map{}
	err = gconv.Struct(res, &resultData)
	if err != nil {
		code = http.StatusInternalServerError
		msg = err.Error()
	}
	resultData[consts.MSgKey] = msg
	resultData[consts.CodeKey] = code
	internalErr := r.Response.WriteJson(resultData)
	if internalErr != nil {
		g.Log().Fatalf(ctx, `%+v`, internalErr)
	}
}
